package com.jack.lib.core.ext

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelChildren

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2020/8/6
 * desc   :
 */
fun Job.lifeRecycle(lifecycle: Lifecycle?): Job = apply {
    lifecycle?.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            if (event == Lifecycle.Event.ON_DESTROY) {
                cancelChildren()
                cancel()
            }
        }
    })
}
